import requests
import json
from pprint import pprint
import shop
import re
def print_foods(shop1):
    for food1 in shop1.foods:
        print(food1.name+'    '+str(food1.price)+'    '+str(food1.packing_fee))
def print_shops(shops):
    for shop1 in shops:
        print("-"*50)
        print(shop1.name)
        print(shop1.tips)
        print(shop1.url)
        print(shop1.delivery_cost)
        print_foods(shop1)
        print('-'*50)
        print()
class EleSpider:
    def __init__(self,phone_num):
        self.phone_num=phone_num
        self.my_account=requests.session()
        self.shops=[]
        self.latitude='23.01755'
        self.longitude="113.414835"
        headers={"user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36",
                 "referer": "https://h5.ele.me/login/",
                 'cookie':"__wpkreporterwid_=4f44ee86-b369-4a28-947f-81cf3d8d499e; ubt_ssid=i5bxwaoogzzde9cbcsbxlum7eryvupd2_2020-09-14; perf_ssid=kyxo0wi7oxcxnt7if27ufqpc6x6vmt3k_2020-09-14; ut_ubt_ssid=o6cgkm8hjj4dxsf1nf2xv1jb0pqugris_2020-09-14; _bl_uid=baka3fey28s4FvnCtgear42syqXq; cna=+ZLgF+yIJx4CAdxzt4NA6vqN; _utrace=a8dc4ccab369fb8d7f61eced9bd8160d_2020-09-14; track_id=1600064076|da71caefac63546b7264a91a049d1f6f5817e1b4ad4d9fd695|d854ecccbc13e0f567062a616c4bba69; UTUSER=877938922; tzyy=4589a60d17bd55bad2738b6199cacd10; USERID=877938922; SID=BwAAAAA0VEjq-QAEAABRBA1xvljDpx1DB0LYBgutERn4J6O1a-N-Bg1a; ZDS=1.0|1600064700|EVXU1jZaVBZhPSZQixJOnNlN2UPQGDj8b7mkJUQAtCnAIoNGHq2cGsUh+V8M9ltFhPY+rZRJQsDFZId9AvjQwA==; x5check_ele=q88E7T44%2FF9uRcNZZr%2FG%2BqzYq8mkg9%2Fao7YUNM6fR94%3D; perf_ssid=iy9bu4vet5lg2a5b6f99wwrpp0jmm88r_2020-09-15; xlly_s=1; x5sec=7b227466653b32223a226162343064623233373133326663333866323330333739366338366364373539434e2f7668667346454b5053774d327939636d504c426f4c4f4463334f544d344f5449794f7a513d227d; l=eBjdqgseOz9MeI7ABOfwourza77OSIRA_uPzaNbMiOCPtTC65SZ5BZrjUyTBC3hRh659R3RZPRigBeYBqIAyiamGhm8WYHkmn; isg=BG1tPVgizq3sXqr_FjNRpo6xfAnnyqGcnAEzeK9yqYRzJo3YdxqxbLvwFfzAoblU; tfstk=ciuhB0TMcDrBQkKakeaIGn82ebpAZ3-ULcni7VYMY6u7-P0NibIN0H1pF-AMSg1.."}
        self.my_account.headers=headers
    def get_code(self):  
        mobile_send_code="https://h5.ele.me/restapi/eus/login/mobile_send_code"
        data={"captcha_hash": "",
              "captcha_value": "",
              "mobile": self.phone_num,
              "scf": "ms"
              }   
        try:
            res=self.my_account.post(mobile_send_code,data=data)
            return json.loads(res.content)['validate_token']
        except:
            print(res.content.decode())
            exit(0)
            #return self.get_code()
    def login(self,validate_code,validate_token):
        login_by_mobile="https://h5.ele.me/restapi/eus/login/login_by_mobile"
        #headers={"user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36"}
        data={"mobile": self.phone_num,
              "scf": "ms",
              "validate_code": validate_code,
              "validate_token": validate_token
              }
        
        res=self.my_account.post(login_by_mobile,data=data)
        a=(res.cookies)
        print(requests.utils.dict_from_cookiejar(a))
    def get_shop(self,page=0):
        params={
            "latitude": self.latitude ,
"longitude": self.longitude         ,
"keyword":  ""                     ,
"offset": str(page*8)                     ,
"limit": "8"                       ,
"extras[]": "activities"           ,
"extras[]": "tags"                 ,
"terminal": "h5"                   ,
"brand_ids[]":""                   ,
"restaurant_category_ids[]": ["770 ",
 "514",
 "1026",
 "1282",
 "263",
 "266",
 "778",
 "522",
 "1034",
 "1290",
 "267",
 "268",
 "269",
 "786",
 "530",
 "1042",
 "1298",
 "794",
 "538",
 "1050",
 "1306",
 "802",
 "546",
 "1058",
 "1314",
 "810",
 "554",
 "1066",
 "1322",
 "818",
 "562",
 "1074",
 "1330",
 "826",
 "570",
 "1082",
 "1338",
 "834",
 "578",
 "1090",
 "1346",
 "842",
 "586",
 "1098",
 "1354",
 "850",
 "594",
 "1106",
 "1362",
 "858",
 "602",
 "346",
 "1114",
 "354",
 "866",
 "610",
 "1122",
 "362",
 "874",
 "618",
 "1130",
 "370",
 "882",
 "626",
 "1138",
 "378",
 "890",
 "634",
 "1146",
 "386",
 "898",
 "642",
 "1154",
 "394",
 "906",
 "650",
 "1162",
 "402",
 "914",
 "658",
 "1170",
 "410",
 "922",
 "666",
 "1178",
 "418",
 "930",
 "674",
 "1186",
 "426",
 "938",
 "682",
 "1194",
 "434",
 "946",
 "690",
 "1202",
 "442",
 "954",
 "698",
 "1210",
 "450",
 "706",
 "962",
 "1218",
 "458",
 "970",
 "714",
 "1226",
 "209",
 "466",
 "978",
 "722",
 "1234",
 "212",
 "214",
 "474",
 "218",
 "986",
 "730",
 "221",
 "222",
 "223",
 "224",
 "225",
 "482",
 "226",
 "994",
 "738",
 "1250",
 "227",
 "228",
 "232",
 "490",
 "746",
 "234",
 "1002",
 "1258",
 "236",
 "240",
 "241",
 "498",
 "754",
 "1010",
 "242",
 "1266",
 "249",
 "762",
 "506",
 "1018",
 "250",
 "1274"]
}
        request_url="https://h5.ele.me/restapi/shopping/v3/restaurants"
        #headers={"user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36","cookie": "ubt_ssid=dfdy3h3k6mr0aagoe8y363mj1ebrl2t2_2019-12-06; cna=ditLFjmUrg8CATspdnTQ5fz8; _utrace=290c589d4bc4ba3005205263d8e0cfc1_2019-12-06; ut_ubt_ssid=84spudsbcw9qldn86rgxq64nvw9i9af9_2019-12-06; perf_ssid=lg90yyx4wjxwnya4cvzpu6u0rr0wowai_2019-12-06; t=a8c43da4f29ff784e8716a9f4b968705; UTUSER=877938922; tzyy=4589a60d17bd55bad2738b6199cacd10; perf_ssid=hc7bqra6sxjc99wk1kn1r1vfxoyf1xko_2020-01-13; __wpkreporterwid_=0a1ac597-c289-4b36-985a-cec525daafd9; _bl_uid=X8kF35CXfs6ce39t584zmndn5qg9; track_id=1579094822|dfe7fc777016ec44100f101db98e9da2f7fd60e5cef6f89357|61b338180f974c0bd2ffa76cc06c7c25; t_eleuc4=id4=0%40BA%2FvuHCrrRkTaiJo84u0xbcGv13wNQCErsVWTw%3D%3D; USERID=877938922; unb=2204905217937; SID=YQQZb2hvS8pQbl5vs7cLgmxFoXFsmd6uqoQQ29; ZDS=1.0|1579359097|mb9G9In6+5moB3NW3dXgN1Kjxg+JSE039CwRbE7OGOu6cU/sxoQyG0m01aZTQFWFIgC6gpby+0mc8fZ5x7JkbA==; x5check_ele=qdq%2FiqF3mxQQHfVtRioFtPcntMrlZL68DpTXaQRo2UU%3D; l=cBSWqtwIq8Rwe5sZBOCiquI8aZ7tRIRfguPRwNXXi_5QT6Kx1s6OomczDFp6cjWh9z8p4082vew9nltuJgT13u4D_dxWi; x5sec=7b227466653b32223a223433343363623762383164383163386363326463663162323165623933333830434f374c6a504546454943416a617235314f373935674561447a49794d4451354d4455794d5463354d7a63374d513d3d227d; isg=BPDwJ-cxWtCADgUeJyBQUCVEwb5COdSD9vrKLOpBvMtGpZBPkkmkE0ab-avFNYxb"}
        #headers={"user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36"}
        res=self.my_account.get(request_url,params=params)
        return (json.loads(res.content.decode()))
        #print(res.url)
        #a=(self.my_account.cookies)
        #pprint(requests.utils.dict_from_cookiejar(a))
    def get_shops(self):
        for j in range(0,20):
            print("正在爬取第{}页店铺".format(j+1))
            temp_shop_info=self.get_shop(j)       
            for i in temp_shop_info['items']:
                temp_shop=i['restaurant']
                temp_shop_name=temp_shop['name']
                if temp_shop['activities']:
                    temp_shop_tips=temp_shop['activities'][0]['tips']
                temp_shop_url=json.loads(temp_shop['business_info'])['pickup_scheme']
                temp_shop_delivery_cost=temp_shop['piecewise_agent_fee']['tips']
                peisong=re.search('\d+',temp_shop_delivery_cost)
                discounts=re.findall("满(\d+)元减(\d+)元",temp_shop_tips)
                flag=True
                for discount in discounts:
                    if int(discount[1])/int(discount[0])>0.4:
                        flag=False
                        break
                if flag:continue
                if peisong:
                    if float(peisong.group())>5:continue
                final_shop=shop.shop(temp_shop_name,temp_shop_tips,temp_shop_url,temp_shop_delivery_cost)
                final_shop.discounts=discounts
                self.shops.append(final_shop)
    def get_foods(self):
        for shop1 in self.shops:
            print("正在爬取{}的商品信息".format(shop1.name))
            params={'terminal': 'h5','user_id':self.my_account.cookies.get('USERID')}
            requests_url="https://h5.ele.me/pizza/shopping/restaurants/{}/batch_shop".format(shop1.url.split("#id=")[1])
            res=self.my_account.get(requests_url,params=params)
            temp_menu=(json.loads(res.content.decode()))['menu']
            for i in temp_menu:
                temp_foods=i['foods']
                for j in temp_foods:
                    if j['activity']!=None:
                        #print (j['activity'])
                        continue
                    temp_food_name=j['name']
                    for k in j['specfoods']:
                        temp_packing_fee=k['packing_fee']
                        temp_price=k['price']
                        shop1.add_food(temp_food_name,temp_price,temp_packing_fee)        
    def save_cookies(self):
        my_cookie=self.my_account.cookies
        my_cookie=json.dumps(requests.utils.dict_from_cookiejar(my_cookie))
        with open(self.phone_num+'cookie.txt','w') as f:
            f.write(my_cookie)
    def read_cookie(self):
        my_cookie=0
        with open(self.phone_num+'cookie.txt','r') as f:
            my_cookie=f.read()
            my_cookie=json.loads(my_cookie)
            my_cookie=requests.utils.cookiejar_from_dict(my_cookie)
            self.my_account.cookies=my_cookie
    def get_address(self,address):
        request_url="https://h5.ele.me/restapi/bgs/poi/search_poi_nearby_alipay"
        params={'keyword': address         ,
                 'offset': '0'             ,
                 'limit': '20'             ,
                 'latitude': '23.12908'    ,
                 'longitude': '113.264359' 
                 }
        res=self.my_account.get(request_url,params=params)
        return(json.loads(res.content.decode()))
    def print_address(self,res):
        print("请选择地址:")
        for i in range(0,len(res)):
            print(i+1,res[i]['name']+"    "+res[i]['address'])
    def make_a_big_discount(self):
        for i in self.shops:
            print("正在凑单:"+i.name)
            for discount in i.discounts:
                print("    满"+discount[0]+"减"+discount[1])
                sum=0
                food_list=[]
                while sum<int(discount[0]):
                    distance=[]
                    target=int(discount[0])-sum
                    for j in i.foods:
                        delta=abs(j.price+j.packing_fee-target)
                        distance.append(delta)
                    add=min(distance)
                    add_index=distance.index(add)
                    while not (i.foods[add_index].price+i.foods[add_index].packing_fee):
                        del distance[add_index]
                        add=min(distance)
                        add_index=distance.index(add)
                    sum+=i.foods[add_index].price+i.foods[add_index].packing_fee
                    food_list.append(add_index)
                i.manjian.append((food_list,sum,discount))
            #i.print_manjian()
    def print_shops_manjian(self):
        for i in self.shops:
            i.print_manjian()
if __name__=='__main__':
    a=EleSpider('13048704663')
    # try:
    #     a.read_cookie()
    # except:
    #     codes=a.get_code()
    #     mycode=input("请输入验证码")
    #     a.login(mycode,codes)
    #     a.save_cookies()
    address=input("请输入地址:")
    res=a.get_address(address)
    if res:
        a.print_address(res)
        num=int(input())
    else:
        print("error")
    a.latitude=res[num-1]['latitude']
    a.longitude=res[num-1]['longitude']
    a.get_shops()
    #a.get_foods()
    #a.make_a_big_discount()
    #a.print_shops_manjian()
    print_shops(a.shops)
        
    

    

